package com.jiajia.study.stack;

/**
 * <h1>局部变量的线程安全问题</h1>
 * @author zjiajia
 * @date 2023/11/12 20:33
 */
public class Demo4 {
    public static void main(String[] args) {
        m1();
        m2(new StringBuilder(2));
        m3();
    }

    /**
     * 局部变量作为返回值传出去了
     * @return
     */
    private static StringBuilder m3() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(1);
        stringBuilder.append(2);
        stringBuilder.append(3);

        System.out.println(stringBuilder.toString());
        return stringBuilder;
    }

    /**
     *
     * 入参可能会被多个线程持有，所有就存在线程安全问题
     *
     * @param stringBuilder
     */
    private static void m2(StringBuilder stringBuilder) {
        stringBuilder.append(1);
        stringBuilder.append(2);
        stringBuilder.append(3);

        System.out.println(stringBuilder.toString());
    }

    private static void m1() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(1);
        stringBuilder.append(2);
        stringBuilder.append(3);

        System.out.println(stringBuilder.toString());
    }

    /**
     * 主线程和 t1 线程都持有 stringBuilder 所有存在线程安全问题
     */
    private static void m4(){
        StringBuilder stringBuilder = new StringBuilder(2);
        new Thread(()->{
            m2(stringBuilder);
        },"t1").start();

        stringBuilder.append(8);
    }

}
